# coding:utf-8

from flask import render_template, request, current_app
from flask_login import login_required

from . import op_bp
from .models import Bill, User
from .bill_forms import SearchBillForm
from .constant import BillSubType


@op_bp.route('/bill_list', methods=['GET', 'POST'])
@login_required
def bill_list():
    """
    created by chenhj at 2017/8/7

    """
    form = SearchBillForm(formdata=request.form or request.args)

    bill_query = Bill.query.filter_by(deleted_at=0)
    url_kwargs = {}
    if form.validate():
        # 如果根据发布者手机号查找，则根据 relationship 查找 Demand
        if form.user_mobile.data:
            owner = User.query.filter_by(
                mobile=form.user_mobile.data, deleted_at=0).first()
            if owner:
                bill_query = owner.bills
            else:
                bill_query = bill_query.filter_by(uid=0)

        _, url_kwargs = form.generate_kwargs()
        # 状态特殊处理(因为他可为0)
        if form.status.data is not None and form.status.data != -1:
            url_kwargs['status'] = form.status.data
        elif 'status' in url_kwargs:
            del url_kwargs['status']

        bill_query = Bill.generate_list_query_condition(
            args=url_kwargs,
            query=bill_query
        )

    page = request.args.get('page', 1, type=int)
    pagination = bill_query.filter(
        Bill.sub_type.in_(
            [
                BillSubType.BUY_PACK.value,
                BillSubType.GIFT_PACK.value,
                BillSubType.INVITE_BUT_PACK_GIFT.value,
                BillSubType.HALF_PACK.value
            ]
        )
    ).order_by(
        Bill.created_at.desc()
    ).paginate(
        page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    bills = pagination.items

    return render_template(
        'bill/bill_list.html',
        form=form,
        bills=bills,
        pagination=pagination,
        url_kwargs=url_kwargs,
    )

